package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.gulimall.auth.vo.GiteeUserInfo;
import com.atguigu.gulimall.auth.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
public class Oauth2Controller {
    @Autowired
    MemberFeignService memberFeignService;


    /**
     * 这里使用码云的oauth2登录，因为码云不需要认证，
     *
     * @param code
     * @return
     * @throws Exception
     */
    @GetMapping("/oauth2.0/gitee/success")
    public String gitee(@RequestParam("code") String code, HttpSession session) throws Exception {
        System.out.println("code:" + code);
        //1.根据code换取accessToken
        //grant_type=authorization_code&code={code}&client_id={client_id}&redirect_uri={redirect_uri}&client_secret={client_secret}
        Map<String, String> header = new HashMap<>();
        Map<String, String> query = new HashMap<>();
        Map<String, String> map = new HashMap<>();
        map.put("grant_type", "authorization_code");
        map.put("code", code);
        map.put("client_id", "2b1857193831715cad8ae96a6409d7c761d6317ede4bf7996a7a3709717dda5b");
        map.put("redirect_uri", "http://auth.gulimall.com/oauth2.0/gitee/success");
        map.put("client_secret", "7c7aaf7c432e60effb7ca5640b3489af34f0af7ff88f1593bc90e9ea6afb7cb0");

        HttpResponse response = HttpUtils.doPost("https://gitee.com", "/oauth/token", "post", header, query, map);

        /**
         * gitee返回参数
         * {
         *     "access_token": "6af670fa9f4386f66b6202bab580c707",
         *     "token_type": "bearer",
         *     "expires_in": 86400,
         *     "refresh_token": "1c49fa711840c19f77a11cab0f26ead6ddf8081b12a1a6b8ec3af9c2803ea435",
         *     "scope": "user_info",
         *     "created_at": 1638084931
         * }
         */

        if (response.getStatusLine().getStatusCode() == 200) {
            String json = EntityUtils.toString(response.getEntity());
            System.out.println(json);
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
            //码云平台需要根据access_token来调用openApi获取uid
            query.put("access_token", socialUser.getAccess_token());
            HttpResponse userApiResponse = HttpUtils.doGet("https://gitee.com", "/api/v5/user", "get", header, query);
            if (userApiResponse.getStatusLine().getStatusCode() == 200) {
                json = EntityUtils.toString(userApiResponse.getEntity());
                GiteeUserInfo giteeUserInfo = JSON.parseObject(json, GiteeUserInfo.class);
                socialUser.setGiteeUserInfo(giteeUserInfo);
                //知道当前是哪个社交用户
                //1.当前用户如果是第一次进网站，自动注册进来(为当前社交用户生成一个会员信息账号,以后这个社交账号就对应)
                //登录或者注册这个
                R oauthlogin = memberFeignService.oauth2login(socialUser);
                if (oauthlogin.getCode() == 0) {
                    MemberRespVo data = oauthlogin.getData("data", new TypeReference<MemberRespVo>() {});
                    //todo 1.默认发的令牌 作用于为当前域(需要解决子域session共享问题)
                    //todo 2.使用json的序列化方式来序列化对象数据到redis中
                    session.setAttribute(AuthServerConstant.LOGIN_USER,data);
                    //2.登录成功就跳回首页
                    return "redirect:http://gulimall.com";
                } else {
                    //失败
                    return "redirect:http://auth.gulimall.com/login.html";
                }
            } else {
                //失败
                return "redirect:http://auth.gulimall.com/login.html";
            }
        } else {
            return "redirect:http://auth.gulimall.com/login.html";
        }


    }
}
